package com.usian.comment.service.impl;

import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.vo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zlm
 * @version 1.0
 * @date 2022/9/24 10:42
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private GreeTextScan greeTextScan;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //参数校验  文章Id和评论内容不为空且评论内容多少有限制
        if (dto.getArticleId() == null || dto.getContent() == null || dto.getContent().length() > 140)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        ApUser user = AppThreadLocalUtils.getUser();//这个对象里只有Id
        if (user == null || user.getId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        try {
            Map map = greeTextScan.greeTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if (!suggestion.equals("pass")) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "这个内容不行，别尼玛瞎评论");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApUser apUser = userFeign.findUserById(user.getId());//这个对象是从表里查出来的
        if (apUser == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());//用户Id
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());//文章ID
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.insert(apComment);
        return ResponseResult.okResult("评论成功");
    }

    //评论点赞
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //检查参数  评论ID
        if (dto.getCommentId() == null || dto.getOperation() < 0 || dto.getOperation() > 1)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //判断是否登录   未登录不能点赞
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        //点赞操作
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);//找到评论
        if (apComment != null && dto.getOperation() == 0) {//第一次点赞
            if (apComment.getLikes() == 1) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "不能重复点赞");
            //更新点赞的数量
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
            //保存app评论信息点赞
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setOperation(dto.getOperation());
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            mongoTemplate.save(apCommentLike);
        } else if (apComment != null && dto.getOperation() == 1) {//在已经点过赞的基础上更新点赞数量
            if (apComment.getLikes() <= 0)
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "还没有点赞怎么取消呢");
            apComment.setLikes(apComment.getLikes() < 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            //更新App评论信息表
            /*
             * 找到 authorId==user.getId(当前登录用户Id) && commentId(评论Id)==apComment.getId()
             * */
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(apComment.getId())), ApCommentLike.class);
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1、检查参数
        if (dto.getArticleId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        int size = 10;
        //2、按照文章Id过滤，设置分页和排序
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);
        //3.数据封装返回
        //3.1 用户未登录 加载数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) ResponseResult.okResult(list);
        //3.2 用户已登录，加载数据，需要判断当前用户点赞了哪些评论
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        List<ApCommentVo> resultList = new ArrayList<>();
        if (list != null && apCommentLikes != null) {
            list.stream().forEach(x -> {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(x, apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (x.getId().equals(apCommentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                        break;
                    }
                }
                resultList.add(apCommentVo);
            });
            return ResponseResult.okResult(resultList);
        } else {
            return ResponseResult.okResult(list);
        }
    }
}
